package org.jeecg.modules.basedata.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.basedata.BaseProject;
import org.jeecg.entity.basedata.BaseProjectInfo;
import org.jeecg.enums.base.DepartPropertyEnum;
import org.jeecg.modules.basedata.service.IBaseProjectInfoService;
import org.jeecg.modules.basedata.service.IBaseProjectService;
import org.jeecg.modules.system.entity.BaseEntity;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.model.TreeSelectModel;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.util.FindsDepartsChildrenUtil;
import org.jeecg.vo.basedata.BaseProjectPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

 /**
 * @Description: 项目
 * @Author: jeecg-boot
 * @Date:   2019-06-18
 * @Version: V1.0
 */
@RestController
@RequestMapping("/b/basedata/baseProject")
@Slf4j
public class BaseProjectController {
	@Autowired
	private IBaseProjectService baseProjectService;
	@Autowired
	private IBaseProjectInfoService baseProjectInfoService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;

	 /**
	  * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	  *
	  * @return
	  */
	 @RequestMapping(value = "/queryProjectTreeList", method = RequestMethod.GET)
	 public Result<List<SysDepartTreeModel>> queryProjectTreeList() {
		 Result<List<SysDepartTreeModel>> result = new Result<>();
		 try {
			 List<SysDepartTreeModel> list = baseProjectService.queryProjectTreeList();
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }



	 /**
	  * 查询数据,并以树结构数据格式响应给前端 - 根据项目ID查询楼宇树
	  *
	  * @return
	  */
	 @GetMapping(value = "/getByFloorTreeList")
	 public Result<List<TreeSelectModel>> getByFloorTreeList(@RequestParam(name="projectId") String projectId) {
		 Result<List<TreeSelectModel>> result = new Result<>();
		 try {
			 List<TreeSelectModel> list = baseProjectService.getByFloorTreeList(projectId);
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }

	 /**
	  * 获取项目列表
	  * @return
	  */
	 @GetMapping(value = "/findProjectList")
	 public Result<List<BaseProject>> findProjectList(){
	 	Result<List<BaseProject>> result = new Result<>();
	 	try {
	 		result.setResult(baseProjectService.findProjectList(null));
	 		result.setSuccess(true);
		}catch (Exception e){
			log.error(e.getMessage(),e);
		}
		 return result;
	 }

	 /**
	  * 查询数据,并以树结构数据格式响应给前端 - 管理处树图  - by liur
	  *
	  * @return
	  */
	 @RequestMapping(value = "/queryOfficeTreeLists", method = RequestMethod.GET)
	 public Result<List<SysDepartTreeModel>> queryProjectTreeListOne(@RequestParam(name = "menuPath",required = false) String menuPath) {
		 Result<List<SysDepartTreeModel>> result = new Result<>();
		 try {
			 List<SysDepartTreeModel> list = new ArrayList<>();
			 if (StringUtils.isNotBlank(menuPath)){
				 //根据权限加载
				 List<SysDepart> departTreeList = sysUserRoleService.queryDepartTreeList(menuPath, SsoUtil.getLoginUser().getId(),CommonConstant.DEPART_WHERE_CO);
				 list = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(departTreeList);
			 } else {
				 list = baseProjectService.queryProjectTreeListOne();
			 }
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }


	 /**
	  * 查询数据,并以树结构数据格式响应给前端 - 管理处树图  - by liur
	  *
	  * @return
	  */
	 @RequestMapping(value = "/queryDepartmentTreeLists", method = RequestMethod.GET)
	 public Result<List<SysDepartTreeModel>> queryDepartmentTreeLists(@RequestParam(name = "menuPath",required = false) String menuPath) {
		 Result<List<SysDepartTreeModel>> result = new Result<>();
		 try {
			 List<SysDepartTreeModel> list = new ArrayList<>();
			 if (StringUtils.isNotBlank(menuPath)){
				 //根据权限加载
				 List<SysDepart> departTreeList = sysUserRoleService.queryDepartTreeList(menuPath, SsoUtil.getLoginUser().getId(),null);
				 list = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(departTreeList);
			 }
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }

	 /**
	  * 查询数据,并以树结构数据格式响应给前端 - 小区项目树图 - by liur
	  *
	  * @return
	  */
	 @RequestMapping(value = "/queryProjectTreeLists", method = RequestMethod.GET)
	 public Result<List<SysDepartTreeModel>> queryProjectTreeLists(@RequestParam(name = "menuPath",required = false) String menuPath) {
		 Result<List<SysDepartTreeModel>> result = new Result<>();
		 try {
			 List<SysDepartTreeModel> list = new ArrayList<>();
			 if (StringUtils.isNotBlank(menuPath)){
				 //根据权限加载
				 List<SysDepart> departTreeList = sysUserRoleService.queryDepartTreeList(menuPath, SsoUtil.getLoginUser().getId(),CommonConstant.DEPART_WHERE_CO);
				 List<String> departIdList = new ArrayList<>();
				 Map<String,SysDepart> departTreeMap= new HashMap<>();
				 List<SysDepartTreeModel> branchList = new ArrayList<>();
				 for (SysDepart departTree: departTreeList){
					 departTreeMap.put(departTree.getId(),departTree);
					 departIdList.add(departTree.getId());
					 if (departTree.getType().equals(DepartPropertyEnum.DEPART_PROPERTY_OFFICE.getCode())) continue;
					 SysDepartTreeModel branch = new SysDepartTreeModel(departTree);
					 branchList.add(branch);
				 }
				 List<DepartIdModel> idList = new ArrayList<>();
				 for (SysDepart depart:departTreeList){
					 if (depart.getType().equals(DepartPropertyEnum.DEPART_PROPERTY_DEPARTMENT.getCode())) continue;
					 if (depart.getType().equals(DepartPropertyEnum.DEPART_PROPERTY_OFFICE.getCode())) continue;
					 if ((StringUtils.isBlank(depart.getParentId())) || (StringUtils.isNotBlank(depart.getParentId()) && !departTreeMap.containsKey(depart.getParentId()))) {
						 SysDepartTreeModel branch = new SysDepartTreeModel(depart);
						 list.add(branch);
						 DepartIdModel departIdModel = new DepartIdModel().convert(branch);
						 idList.add(departIdModel);
					 }
				 }
				 if (departTreeList.size() > 0){
					 List<SysDepart> projectTreeList =  sysUserRoleService.queryProjectTreeListByDepartId(departIdList);
					 for (SysDepart project:projectTreeList){
						 SysDepartTreeModel branch = new SysDepartTreeModel(project);
						 branchList.add(branch);
					 }
					 FindsDepartsChildrenUtil.getGrandChildren(list,branchList,idList);
					 FindsDepartsChildrenUtil.setEmptyChildrenAsNull(list);
				 }
			 } else {
				 list = baseProjectService.queryProjectTreeLists();
			 }
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }

	 /**
	  * 查询数据,并以下拉框结构数据格式响应给前端 - 小区项目 下拉框 - by liur
	  *
	  * @return
	  */
	 @RequestMapping(value = "/queryProjectLists", method = RequestMethod.GET)
	 public Result<List<SysDepart>> queryProjectLists(@RequestParam(name = "menuPath",required = false) String menuPath) {
		 Result<List<SysDepart>> result = new Result<>();
		 try {
			 List<SysDepart> list = new ArrayList<>();
			 if (StringUtils.isNotBlank(menuPath)){
				 //根据权限加载
				 List<SysDepart> departTreeList = sysUserRoleService.queryDepartTreeList(menuPath, SsoUtil.getLoginUser().getId(),CommonConstant.DEPART_WHERE_CO);
				 List<String> departIdList = new ArrayList<>();
				 for (SysDepart departTree: departTreeList){
					 departIdList.add(departTree.getId());
				 }
				 if (departTreeList.size() > 0){
					list =  sysUserRoleService.queryProjectTreeListByDepartId(departIdList);
				 }
			 } else {
//				 list = baseProjectService.queryProjectTreeLists();
			 }
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }

	 @RequestMapping(value = "/queryDepartmentTreeByKeywords", method = RequestMethod.GET)
	 public Result<List<SysDepartTreeModel>> queryDepartmentTreeByKeywords(@RequestParam(name = "keyWord", required = true) String keyWord,@RequestParam(name = "menuPath",required = false) String menuPath) {
		 Result<List<SysDepartTreeModel>> result = new Result<>();
		 try {
			 List<SysDepartTreeModel> list = new ArrayList<>();
			 if (StringUtils.isNotBlank(menuPath)){
				 //根据权限加载
				 List<SysDepart> departTreeList = sysUserRoleService.queryDepartTreeListByKeywords(keyWord,menuPath, SsoUtil.getLoginUser().getId(),null);
				 list = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(departTreeList);
			 }
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }


	 /**
	  * 根据关键词查询小区列表数据,并以树结构数据格式响应给前端
	  *
	  * @return
	  */
	 @RequestMapping(value = "/queryProjectTreeByKeywords")
	 public Result<List<SysDepartTreeModel>> queryProjectTreeByKeywords(@RequestParam(name = "keyWord", required = true) String keyWord,@RequestParam(name = "menuPath", required = true) String menuPath) {
		 Result<List<SysDepartTreeModel>> result = new Result<>();
		 try {
			 BaseEntity baseEntity = new BaseEntity();
			 baseEntity.setMenuPath(menuPath);
			 baseEntity.setDepartIdEx("");
			 List<String> projectIds = sysUserRoleService.queryProjectIds(baseEntity);
			 List<SysDepartTreeModel> list = baseProjectService.queryProjectTreeByKeywords(keyWord,projectIds);
			 if(list != null && list.size() > 0){
			 	for (SysDepartTreeModel model : list){
			 		model.setKey(model.getId());
			 		model.setValue(model.getId());
			 		model.setTitle(model.getDepartName());
					model.setIsLeaf(true);
				}
			 }
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }

	 /**
	  * 根据关键词查询管理处列表数据,并以树结构数据格式响应给前端
	  *
	  * @return
	  */
	 @RequestMapping(value = "/queryOfficeTreeByKeywords")
	 public Result<List<SysDepartTreeModel>> queryOfficeTreeByKeywords(@RequestParam(name = "keyWord", required = true) String keyWord,@RequestParam(name = "menuPath", required = true) String menuPath) {
		 Result<List<SysDepartTreeModel>> result = new Result<>();
		 try {
			 BaseEntity baseEntity = new BaseEntity();
			 baseEntity.setMenuPath(menuPath);
			 baseEntity.setDepartIdEx("");
			 List<String> officeIds = sysUserRoleService.queryOfficeIds(baseEntity);
			 List<SysDepartTreeModel> list = baseProjectService.queryOfficeTreeByKeywords(keyWord,officeIds);
			 if(list != null && list.size() > 0){
				 for (SysDepartTreeModel model : list){
					 model.setIsLeaf(true);
					 model.setKey(model.getId());
					 model.setValue(model.getId());
					 model.setTitle(model.getDepartName());
				 }
			 }
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }

	/**
	  * 分页列表查询
	 * @param baseProject
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<BaseProject>> queryPageList(BaseProject baseProject,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<BaseProject>> result = new Result<IPage<BaseProject>>();
		try{
			if (CommonConstant.DEPART_PROPERTY_PROJECT.equals(baseProject.getDepartType())){
				baseProject.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(),"p",baseProject.getMenuPath(),null,null));
			} else {
				baseProject.setSqlMap(sysUserRoleService.dataScopeDepartOnlyFilter(SsoUtil.getLoginUser(),"d",baseProject.getMenuPath(),null,null));
			}
			Page<BaseProject> pageList = new Page<BaseProject>(pageNo, pageSize);
			if(StringUtils.isNotEmpty(baseProject.getDepartId())){
				pageList = baseProjectService.listByParams(pageList,baseProject);
			}
			result.setSuccess(true);
			result.setResult(pageList);
		}catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}

		return result;
	}

	 /**
	  * 查询小区是否有楼宇绑定
	  * @param baseProject
	  * @return
	  */
	 @GetMapping(value = "/getFloorCount")
	 public Result<Integer> getFloorCount(BaseProject baseProject) {
		 Integer count = 0;
		 try{
			 count= baseProjectService.getFloorCount(baseProject.getId());
			 return Result.ok(count);
		 }catch (Exception e ){
			 e.printStackTrace();
			 return Result.error("内部异常");
		 }
	 }
	
	/**
	  *   添加
	 * @param baseProjectPage
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<BaseProject> add(@RequestBody BaseProjectPage baseProjectPage) {
		Result<BaseProject> result = new Result<BaseProject>();
		try {
			BaseProject baseProject = new BaseProject();
			BeanUtils.copyProperties(baseProjectPage, baseProject);

			BaseProjectInfo baseProjectInfo = new BaseProjectInfo();
			BeanUtils.copyProperties(baseProjectPage, baseProjectInfo);
			
			baseProjectService.saveMain(baseProject, baseProjectInfo);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param baseProjectPage
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<BaseProject> edit(@RequestBody BaseProjectPage baseProjectPage) {
		Result<BaseProject> result = new Result<BaseProject>();
		try {
			BaseProject baseProject = new BaseProject();
			BeanUtils.copyProperties(baseProjectPage, baseProject);
			BaseProjectInfo baseProjectInfo = new BaseProjectInfo();
			BeanUtils.copyProperties(baseProjectPage, baseProjectInfo);
			BaseProject baseProjectEntity = baseProjectService.getById(baseProject.getId());
			if (baseProjectEntity == null) {
				result.error500("未找到对应实体");
			} else {
				boolean ok = baseProjectService.updateById(baseProject);
				if(StringUtils.isNotEmpty(baseProjectInfo.getAddress())){
					baseProjectService.updateMain(baseProject, baseProjectInfo);
				}
				result.success("修改成功!");
			}
		}catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<BaseProject> delete(@RequestParam(name="id",required=true) String id) {
		Result<BaseProject> result = new Result<BaseProject>();
		BaseProject baseProject = baseProjectService.getById(id);
		if(baseProject==null) {
			result.error500("未找到对应实体");
		}else {
			baseProjectService.delMain(id);
			result.success("删除成功!");
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<BaseProject> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<BaseProject> result = new Result<BaseProject>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.baseProjectService.delBatchMain(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}

	 /**
	  *  批量删除判断小区下是否有楼宇绑定
	  * @param ids
	  * @return
	  */
	 @GetMapping(value = "/getFloorCounts")
	 public Result<Integer> getFloorCounts(@RequestParam(name="ids",required=true) String ids) {
		 Integer count = 0;
		 try{
			 String[] split = ids.split(",");
			 count= baseProjectService.getFloorCounts(split);
			 return Result.ok(count);
		 }catch (Exception e ){
			 e.printStackTrace();
			 return Result.error("内部异常");
		 }
	 }
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<BaseProjectPage> queryById(@RequestParam(name="id",required=true) String id) {
		Result<BaseProjectPage> result = new Result<BaseProjectPage>();
		try {
			BaseProjectPage baseProjectPage = baseProjectService.selectByMainId(id);
			if (baseProjectPage == null) {
				result.error500("未找到对应实体");
			} else {
				result.setResult(baseProjectPage);
				result.setSuccess(true);
			}
		}catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response, BaseProject baseProject) {
	  LoginUser user = SsoUtil.getLoginUser();
	  baseProject.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(),"p",baseProject.getMenuPath(),null,baseProject.getDepartIdEx()));
	  Page<BaseProject> page = new Page<BaseProject>(1, baseProjectService.list().size());
      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<BaseProjectPage> pageList = new ArrayList<BaseProjectPage>();
	  Page<BaseProject> baseProjectList = baseProjectService.listByParams(page, baseProject);
      for (BaseProject b : baseProjectList.getRecords()) {
          BaseProjectPage vo = new BaseProjectPage();
          BeanUtils.copyProperties(b, vo);
          BaseProjectInfo baseProjectInfo = baseProjectInfoService.selectByMainId(b.getId());
		  if (baseProjectInfo != null){
			  BeanUtils.copyProperties(baseProjectInfo, vo);
		  }
          pageList.add(vo);
      }
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "项目列表");
      mv.addObject(NormalExcelConstants.CLASS, BaseProjectPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("项目列表数据", "导出人:" + user.getRealname(), "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<BaseProjectPage> list = ExcelImportUtil.importExcel(file.getInputStream(), BaseProjectPage.class, params);
              for (BaseProjectPage page : list) {
                  BaseProject po = new BaseProject();
                  BeanUtils.copyProperties(page, po);
				  BaseProjectInfo poInfo = new BaseProjectInfo();
				  BeanUtils.copyProperties(page, poInfo);
                  baseProjectService.saveMain(po, poInfo);
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
